import React, { useState } from 'react'
import { Form, Input, Button, Checkbox, message, Typography, Divider } from 'antd'
import { UserOutlined, LockOutlined, MailOutlined, WechatOutlined, QqOutlined } from '@ant-design/icons'
import { useNavigate, Link } from 'react-router-dom'
import { useUserStore } from '@/stores'
import { useBreakpoint } from '@/hooks/useBreakpoint'
import './style.css'

const { Text } = Typography

interface RegisterForm {
  email: string
  username: string
  password: string
  confirmPassword: string
  agreement: boolean
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const { register } = useUserStore()
  const breakpoint = useBreakpoint()
  const isMobile = breakpoint === 'mobile'

  const onFinish = async (values: RegisterForm) => {
    setLoading(true)
    try {
      await register(values.email, values.username, values.password)
      message.success('注册成功！')
      navigate('/projects')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '注册失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      <h2 className={`font-bold text-center mb-6 ${isMobile ? 'text-2xl' : 'text-3xl'}`}>
        用户注册
      </h2>
      <Form
        name="register"
        onFinish={onFinish}
        layout="vertical"
        size={isMobile ? 'large' : 'middle'}
        scrollToFirstError
      >
        <Form.Item
          name="email"
          rules={[
            { required: true, message: '请输入邮箱！' },
            { type: 'email', message: '请输入有效的邮箱地址！' }
          ]}
          hasFeedback
        >
          <Input
            prefix={<MailOutlined />}
            placeholder="邮箱"
            autoComplete="email"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item
          name="username"
          rules={[
            { required: true, message: '请输入用户名！' },
            { min: 3, max: 20, message: '用户名长度应为3-20个字符！' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线！' }
          ]}
          hasFeedback
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="用户名（3-20个字符）"
            autoComplete="username"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            { required: true, message: '请输入密码！' },
            { min: 8, message: '密码至少8个字符！' },
            {
              pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
              message: '密码必须包含字母和数字！'
            }
          ]}
          hasFeedback
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码（至少8个字符，包含字母和数字）"
            autoComplete="new-password"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          dependencies={['password']}
          rules={[
            { required: true, message: '请确认密码！' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error('两次输入的密码不一致！'))
              },
            }),
          ]}
          hasFeedback
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="确认密码"
            autoComplete="new-password"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item
          name="agreement"
          valuePropName="checked"
          rules={[
            {
              validator: (_, value) =>
                value ? Promise.resolve() : Promise.reject(new Error('请同意服务条款')),
            },
          ]}
        >
          <Checkbox style={{ fontSize: isMobile ? '16px' : '14px' }}>
            我已阅读并同意 <a href="#">服务条款</a> 和 <a href="#">隐私政策</a>
          </Checkbox>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            className="w-full"
            style={{ minHeight: isMobile ? '44px' : '32px' }}
          >
            注册
          </Button>
        </Form.Item>

        <div className="text-center" style={{ fontSize: isMobile ? '16px' : '14px' }}>
          已有账号？ <Link to="/auth/login">立即登录</Link>
        </div>
      </Form>

      {isMobile && (
        <>
          <Divider className="my-4">或</Divider>

          <div className="space-y-2">
            <Button
              icon={<WechatOutlined />}
              size="large"
              className="w-full hover:opacity-90"
              style={{
                backgroundColor: '#07C160',
                color: 'white',
                border: 'none',
                minHeight: '44px'
              }}
              onClick={() => message.info('微信注册功能开发中')}
            >
              微信快速注册
            </Button>
            <Button
              icon={<QqOutlined />}
              size="large"
              className="w-full hover:opacity-90"
              style={{
                backgroundColor: '#12B7F5',
                color: 'white',
                border: 'none',
                minHeight: '44px'
              }}
              onClick={() => message.info('QQ注册功能开发中')}
            >
              QQ快速注册
            </Button>
          </div>
        </>
      )}
    </>
  )
}

export default RegisterPage
